package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	"mxshop_srvs/user_srv/model"
	"mxshop_srvs/user_srv/setting"
)

func main() {
	setting.InitConfig()
	conf := setting.Conf.MysqlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		conf.User, conf.Password, conf.Host, conf.Port, conf.Database)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		},
	)

	// 全局模式
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	// 设置全局的logger，这个logger在我们执行每个sql语句的时候会打印每一行sql
	// sql才是最重要的，本着这个原则我尽量的给大家看到每个api背后的sql语句是什么

	// 定义一个表结构， 将表结构直接生成对应的表 - migrations
	// 迁移 schema
	_ = db.AutoMigrate(&model.User{}) // 此处应该有sql语句

	// 往开发用的数据库插入一些数据
	password := "123456"
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	newPassword := string(hash)
	fmt.Println(newPassword)

	for i := 0; i < 10; i++ {
		user := model.User{
			NickName: fmt.Sprintf("Dugong%d", i),
			Mobile:   fmt.Sprintf("1878100860%d", i),
			Password: newPassword,
		}
		db.Save(&user)
	}
}
